package com.wkbb.sports.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.wkbb.common.base.BaseController;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.constants.RedisKeyConstant;
import com.wkbb.common.constants.VersionConstant;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.*;
import com.wkbb.common.handler.JsonUtil;
import com.wkbb.common.redis.RedisTemplateUtil;
import com.wkbb.common.utils.IdCardUtil;
import com.wkbb.common.utils.MD5Util;
import com.wkbb.common.utils.TokenUtil;
import com.wkbb.sports.dto.LekangResultDto;
import com.wkbb.sports.dto.TrainDto;
import com.wkbb.sports.feign.BasicFeignService;
import com.wkbb.sports.model.*;
import com.wkbb.sports.service.HaokangService;
import com.wkbb.sports.service.LekangService;
import com.wkbb.sports.utils.HttpRequestUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@Api(description = "浩言健康主机使用")
@RequestMapping("/sports/{apiVersion}/haokang")
@Slf4j
public class HaokangController extends BaseController {

    private final String BASE_URL = "http://open.haokangyun.com/";
    private final String CREATE_USER_URL = BASE_URL + "open/userinfo/create";
    @Autowired
    private HaokangService haokangService;
    @Autowired
    private BasicFeignService basicFeignService;

    @ApiOperation(value = "开始测试(浩言健康主机)")
    @RequestMapping(value = "/startExamine", method = RequestMethod.POST)
    public ResultDTO getBannerListByPage(@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
                                         @ApiParam(value = "学生ID", required = true) @RequestParam(name = "studentId", required = true) Long studentId,
                                         @ApiParam(value = "设备标识", required = true) @RequestParam(name = "deviceCode", required = true) String deviceCode,
                                         @ApiParam(value = "场馆标识", required = true) @RequestParam(name = "gymId", required = true) Long gymId) {
        try {
            UserDto userDto = this.getRouteUserByUnion();
            if (null == userDto) {
                return new ResultDTO(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            ResultDTO<StudentInfoDto> resultDTO = basicFeignService.getStudentByFamily(studentId,userDto.getId());
            if (resultDTO.isSuccess()){
                StudentInfoDto studentInfoDto = resultDTO.getData();
                if (!studentInfoDto.getHasFaceRecognition()){
                    return ResultDTO.errorResult("未进行实名认证，无法开始测试");
                }
//                HkExamine hkExamine = new HkExamine();
//                hkExamine.setGymId(gymId);
                HkOpenUserInfo info = new HkOpenUserInfo();
                info.setName(studentInfoDto.getName());
                info.setThirdId(String.valueOf(studentInfoDto.getUserId()));
                String idcard = studentInfoDto.getIdCard();
                info.setIdcard(idcard);
                info.setPhone(userDto.getMobile());
                info.setAge(String.valueOf(IdCardUtil.getAge(idcard)));
                info.setBirthday(IdCardUtil.getBirthday(idcard));
//                info.setSex(IdCardUtil.getSex(idcard));
                info.setSex("男".equals(IdCardUtil.getSex(idcard)) ? "1":"2");
                info.setDeviceCode(deviceCode);
//                hkExamine.setInfo(info);
                String jsonString = JsonUtil.objectToJson(info);
//                log.info("------------------hkExamine:{}",jsonString);
                String resultJson = HttpRequestUtil.post(CREATE_USER_URL + "?gymId="+gymId,jsonString);
                JSONObject result = JsonUtil.jsonToClass(resultJson,JSONObject.class);
//                log.info("------------------result:{}",result);
                return ResultDTO.successResult(result.getString("data"));
            }
            return resultDTO;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResultDTO<>(false);
    }

    @ApiOperation(value = "接收主机检查结果")
    @RequestMapping(value = "/putExamineReport", method = RequestMethod.POST)
    public ResultDTO putExamineReport(@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
                                      @RequestBody HkBody data) {
        try {
            log.info("***********HaokangController.putExamineReport******:{}", JsonUtil.objectToJson(data));
            return haokangService.putExamineReport(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResultDTO<>(false);
    }


    @ApiOperation(value = "获取检查结果详情")
    @RequestMapping(value = "/getExamineReport", method = RequestMethod.GET)
    public ResultDTO<HkBody> putExamineReport(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "体测标识", required = false) @PathVariable(value = "measureId", required = false) Long measureId,
            @ApiParam(value = "学生标识", required = false) @PathVariable(value = "studentId", required = false) Long studentId) {
        try {
//            log.info("***********HaokangController.putExamineReport******:{}", JsonUtil.objectToJson(data));
            Map<String,Object> params = new HashMap<>();
            params.put("measureId", measureId);
            params.put("studentId", studentId);
            return haokangService.getExamineReport(params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResultDTO<>(false);
    }


}
